﻿using CalendarWindowsApp.Tools;
using System.Linq;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;

namespace CalendarWindowsApp.Behaviors
{
    public class DynamicPanelSizeBehavior : BehaviorBase
    {
        private const double HEIGHT_OFFSET = 10.0;
        private double headerHeight = 0;
        private int columns = 0;
        private int rows = 0;

        protected override void OnAttached()
        {
            base.OnAttached();

            var panel = AssociatedObject as ItemsWrapGrid;
            panel.Loaded += (s, e) =>
            {
                var parentContainer = panel.TryFindParent<GridView>() != null ?
                    panel.TryFindParent<GridView>() :
                    panel.TryFindParent<ItemsControl>();

                var collectionSource = parentContainer.ItemsSource as ICollectionView;
                this.columns = collectionSource.CollectionGroups.Count;
                this.rows = collectionSource.Count / collectionSource.CollectionGroups.Count;

                if (parentContainer is GridView)
                {
                    var containerHeader =
                        panel.Children.First(item => item is GridViewHeaderItem) as GridViewHeaderItem;
                    if (containerHeader != null)
                        this.headerHeight = containerHeader.ActualHeight;
                    (parentContainer as GridView).SelectionChanged += (gridView, attEvent) =>
                    {
                        collectionSource = parentContainer.ItemsSource as ICollectionView;
                        this.columns = collectionSource.CollectionGroups.Count;
                        this.rows = collectionSource.Count / collectionSource.CollectionGroups.Count;
                        // Call the size changed to create fit in to the new number of rows in the month view.
                        this.OnViewSizeChanged(parentContainer, null);
                    };
                }
                parentContainer.SizeChanged += OnViewSizeChanged;
                panel.MaximumRowsOrColumns = this.columns;
                var panelItemsHeight = parentContainer.ActualHeight - HEIGHT_OFFSET - this.headerHeight;
                panel.ItemWidth = parentContainer.ActualWidth / this.columns;
                panel.ItemHeight = panelItemsHeight / this.rows;
            };
        }

        private void OnViewSizeChanged(object sender, Windows.UI.Xaml.SizeChangedEventArgs e)
        {
            var container = sender is GridView ?
                sender as GridView :
                sender as ItemsControl;
            var panel = AssociatedObject as ItemsWrapGrid;
            var panelItemsHeight = container.ActualHeight - HEIGHT_OFFSET - this.headerHeight;
            panel.ItemWidth = container.ActualWidth / this.columns;
            panel.ItemHeight = panelItemsHeight / rows;
        }
    }
}